package cn.yechen.yygh.email.controller;

import cn.yechen.yygh.common.result.Result;
import cn.yechen.yygh.email.service.EmailService;
import cn.yechen.yygh.email.uitl.RandomCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author yechen
 * @create 2021-08-21 13:01
 */
@Api(tags = "邮件发送模块")
@RestController
@RequestMapping("/api/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("发送邮件验证码")
    @GetMapping("/sendEmail/{phone}")
    public Result sendEmail(@PathVariable String phone) {
        // 生成验证码
        String code = RandomCodeUtil.getSixBitRandom();

        // 发送验证码
        boolean result = emailService.sendCode(phone, code);

        // 存储验证码到 redis 中，并返回结果
        if (result) {
            redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送邮件失败");
        }
    }



}
